//
//  String+Extension.swift
//  SK_BasePrivateProject
//
//  Created by Regina on 2018/10/08.
//  Copyright © 2018年 Regina. All rights reserved.
//

import UIKit

extension String {
    ///判断字符串是否为空
    public func isBlank() -> Bool {
        
        var newString = self;
        
        if newString.isEmpty {
            return true
        }
        
        newString = newString.trimmingWhiteSpaceCharacters()
        
        if newString.isEmpty {
            return true
        }
        return false
    }
    
    ///判断是否是手机号
    public func isMobilePhoneNumber() -> Bool {
        
        let mobile = "^1((3[0-9]|4[57]|5[0-35-9]|7[0678]|8[0-9])\\d{8}$)"
        
        let  CM = "(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
        
        let  CU = "(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
        
        let  CT = "(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
        
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobile)
        let regextestcm = NSPredicate(format: "SELF MATCHES %@",CM )
        let regextestcu = NSPredicate(format: "SELF MATCHES %@" ,CU)
        let regextestct = NSPredicate(format: "SELF MATCHES %@" ,CT)
        
        if ((regextestmobile.evaluate(with: self) == true)
            || (regextestcm.evaluate(with: self)  == true)
            || (regextestct.evaluate(with: self) == true)
            || (regextestcu.evaluate(with: self) == true)) {
            return true
        } else {
            return false
        }
    }
    
    ///判断密码是否数字和字母组合组成， 默认6-16位
    public func isPassword(minNumber: Int = 6, maxNumber: Int = 16) -> Bool {
        
        let rule = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{" + String(minNumber) + "," + String(maxNumber) + "}$"
        let regextestpwd = NSPredicate(format: "SELF MATCHES %@",rule)
        if (regextestpwd.evaluate(with: self) == true) {
            return true
        } else {
            return false
        }
    }
    
    ///判断是否是邮箱
    public func isEmail() -> Bool {
        
        let rule = "^([a-z0-9_//.-]+)@([//da-z//.-]+)//.([a-z//.]{2,6})$"
        let regextestpwd = NSPredicate(format: "SELF MATCHES %@",rule)
        if (regextestpwd.evaluate(with: self) == true) {
            return true
        } else {
            return false
        }
    }
    
    ///判断是否包含表情
    public func containsEmoji() -> Bool {
        for scalar in unicodeScalars {
            switch scalar.value {
            case 0x1F600...0x1F64F, // Emoticons
            0x1F300...0x1F5FF,      // Misc Symbols and Pictographs
            0x1F680...0x1F6FF,      // Transport and Map
            0x2600...0x26FF,        // Misc symbols
            0x2700...0x27BF,        // Dingbats
            0xFE00...0xFE0F:        // Variation Selectors
                return true
            default:
                continue
            }
        }
        return false
    }
    
    ///去掉字符串中的空格及换行符
    public func trimmingWhiteSpaceCharacters() -> String {
        
        var newString = self;
        newString = newString.replacingOccurrences(of: "\r", with: "")
        newString = newString.replacingOccurrences(of: "\n", with: "")
        newString = self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
        newString = newString.replacingOccurrences(of: " ", with: "")
        return newString;
    }
    
    ///去掉字符串中的特殊字符
    public func trimmingSpecialCharacters() -> String {
        
        var newString = self;
        let charactersSet: CharacterSet = CharacterSet.init(charactersIn: "@／:：;；()（）!！,，.。¥￥“”‘’//「」＂、【】[]{}｛｝—～《》… <>?？#%-*+=_\\|~＜＞$€^·\'#$%^&*()_+'\"");
        newString = newString.trimmingCharacters(in: charactersSet);
        return newString;
    }
    
    ///去掉字符串中的表情
    public func trimmingEmojiCharacters() -> String {
        
        var newString = self;
        
        let regex = try!NSRegularExpression.init(pattern: "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]", options: .caseInsensitive)
        
        newString = regex.stringByReplacingMatches(in: newString, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSRange.init(location: 0, length: newString.count), withTemplate: "")
        
        return newString;
    }
    
    ///获取子字符串
    public func subStringInRange(_ r: Range<Int>) -> String? {
        if r.lowerBound < 0 || r.upperBound > self.count {
            return nil
        }
        let startIndex = self.index(self.startIndex, offsetBy:r.lowerBound)
        let endIndex   = self.index(self.startIndex, offsetBy:r.upperBound)
        return String(self[startIndex..<endIndex])
    }
    
    public func subStringToIndex(_ index: Int) -> String? {
        let count = self.count
        if count < index {
            return self
        }
        let index = self.index((self.startIndex), offsetBy: index)
        return String(self[..<index])
    }
    
    ///手机号添加空格
    public func phoneNumberFormat() -> String? {
        
        var phone = self.trimmingWhiteSpaceCharacters()
        let length = phone.count
        
        if length <= 3 {
            return phone
        } else if length <= 7 {
            phone.insert(" ", at: phone.index(phone.startIndex, offsetBy: 3))
            return phone
        } else if length <= 11 {
            phone.insert(" ", at: phone.index(phone.startIndex, offsetBy: 3))
            phone.insert(" ", at: phone.index(phone.startIndex, offsetBy: 8))
            return phone
        } else {
            let index = phone.index((phone.startIndex), offsetBy: 11)
            phone = String(phone[..<index])
            phone.insert(" ", at: phone.index(phone.startIndex, offsetBy: 3))
            phone.insert(" ", at: phone.index(phone.startIndex, offsetBy: 8))
            return phone
        }
    }
    
    //使用正则表达式替换
    public func replaceWithRegular(pattern: String, with: String,
                     options: NSRegularExpression.Options = []) -> String {
        let regex = try! NSRegularExpression(pattern: pattern, options: options)
        return regex.stringByReplacingMatches(in: self, options: [],
                                              range: NSMakeRange(0, self.count),
                                              withTemplate: with)
    }
    
    /*
     非中文：[^\\u4E00-\\u9FA5]
     非英文：[^A-Za-z]
     非数字：[^0-9]
     非中文或英文：[^A-Za-z\\u4E00-\\u9FA5]
     非英文或数字：[^A-Za-z0-9]
     非因为或数字或下划线：[^A-Za-z0-9_]
    */
    
    //将汉字转为拼音
    public func pinyin() -> String {
        
        let mutableString = NSMutableString(string: self)
        //把汉字转为拼音
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        //去掉拼音的音标
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        
        var string = String(mutableString)
        //去掉空格
        string = string.trimmingWhiteSpaceCharacters()
        //转为小写
        string = string.lowercased()
        
        return string
    }

}
